import { DataBase, DataStructure, _ } from "./database";
import { DeviceList } from "./deviceList";


/** 设备分组 */
export class DeviceGroup extends DataBase {
    public static collectionName: string = "DeviceGroup";

    /** 组名 */
    public name: string;
    /** 说明 */
    public explain: string;
    /** 分组的成员 */
    public members: string[];
    /** 是否允许删除 */
    public allowDelete: boolean;

    constructor(data: DataStructure = {}) {
        super(data);
        this.name = data['name'] || ""
        this.explain = data['explain'] || ""
        this.allowDelete = data['allowDelete'] === true ? true : false
        this.members = data['members'] || []
        this.members = this.members.map(x => x.toString())
    }

    /** 获取所有组群 */
    public static async GetDeviceGroup() {
        const a = await this.GetAllData({
            _openid: '{openid}',
        });
        return a.map(x => new DeviceGroup(x));
    }

    /**
     * 创建一个分组
     * @param name 组名
     * @param explain 说明
     */
    public static async CreateDeviceGroup(name: string, explain: string = '', allowDelete: boolean = true) {
        const a = await this.AddData(new DeviceGroup({
            name,
            explain,
            allowDelete
        }))
        return a
    }


    /** 删除分组 */
    public async Remove(replaceId: string) {
        console.log("删除分组", this.get_id());

        await DeviceList.UpdateDataInWhere2({
            groupId: replaceId
        }, {
            groupId: this.get_id()
        })
        return await DeviceGroup.RemoveDataInWhere({
            _id: this.get_id(),
            _openid: '{openid}',
        })
    }
}